package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import io.minio.*;
import io.minio.errors.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;

/**
 * @author tongatong
 * @name FileUploadController
 * @description
 * @date 2021/9/12
 * @time 18:44
 */
@Api(tags = "文件上传接口")
@RestController
@RequestMapping("admin/product")
public class FileUploadController {
    //  获取文件上传对应的地址
    @Value("${minio.endpointUrl}")
    public String endpointUrl;
    @Value("${minio.bucketName}")
    private String bucketName;
    @Resource
    private MinioClient minioClient;

    //文件上传控制器
    @ApiOperation("文件上传")
    @PostMapping("fileUpload")
    public Result<String> fileUpload(MultipartFile file) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
        //初始化文件上传后返回的URL
        String url;

        //存在为true，不存在为false
        boolean isExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());

        //存在
        if (isExists) {
            System.out.println("Bucket already exists.");
        }else {
            //新建一个桶，存储图片
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
        //定义文件上传的名字
        String fileName = String.valueOf(Instant.now().toEpochMilli());

        minioClient.putObject(
                PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(
                        file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build());

        url = endpointUrl+"/"+bucketName+"/"+fileName;

        return Result.ok(url);

    }



}
